package cz.muni.fi.pa165.sportclubmanager.dao;

import cz.muni.fi.pa165.sportclubmanager.entity.AgeCategory;
import cz.muni.fi.pa165.sportclubmanager.entity.Team;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 * JPA implementation of TeamDAO.
 *
 * @author Jan Bliznak
 */
@Repository
public class TeamDAOImpl implements TeamDAO {

    @PersistenceContext
    private EntityManager em;

    public TeamDAOImpl() {       
    }

    private void checkTeamId(Team t) {
        if (t.getId() == null) {
            throw new IllegalArgumentException("team id cannot be null");
        }
    }

    private void checkTeamFields(Team t) {
        if (t.getName() == null) {
            throw new IllegalArgumentException("Team name must be set");
        }
        if (t.getName().length() > 255) {
            throw new IllegalArgumentException("Max length of team name is limited to 255");
        }

        if (t.getAgeCategory() == null) {
            throw new IllegalArgumentException("Age category must be set");
        }
    }

    @Override
    public void create(Team t) {
        if (t == null) {
            throw new IllegalArgumentException("t cannot be null");
        }
        checkTeamFields(t);

        em.persist(t);
    }

    @Override
    public void update(Team t) {
        if (t == null) {
            throw new IllegalArgumentException("t cannot be null");
        }
        checkTeamId(t);
        checkTeamFields(t);

        em.merge(t);
    }

    @Override
    public void remove(Team t) {
        if (t == null) {
            throw new IllegalArgumentException("t cannot be null");
        }
        checkTeamId(t);

        Team merge = em.merge(t);
        em.remove(merge);
    }

    @Override
    public Team find(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("team id cannot be null");
        }

        Team t = em.find(Team.class, id);
        return t;
    }

    @Override
    public List<Team> findAll() {
        Query query = em.createQuery("SELECT t FROM Team t");
        List<Team> teams = (List<Team>) query.getResultList();

        return teams;
    }

    @Override
    public List<Team> findByAgeCategory(AgeCategory ageCategory) {
        if (ageCategory == null) {
            throw new IllegalArgumentException("ageCategory cannot be null");
        }
        if (ageCategory.getId() == null) {
            throw new IllegalArgumentException("ageCategory's id cannot be null");
        }

        Query query = em.createQuery("SELECT t FROM Team t WHERE t.ageCategory = ?1 ");
        query.setParameter(1, ageCategory);
        List<Team> teams = (List<Team>) query.getResultList();

        return teams;
    }
}
